//
//  AppDelegate+Jpush.m
//  MiaoKong
//
//  Created by EDZ on 2017/8/8.
//  Copyright © 2017年 EDZ. All rights reserved.
//

#import "LJAppDelegate+Jpush.h"

#import "AppDelegate+AppService.h"

@implementation AppDelegate (Jpush)

- (void)initJpush:(UIApplication *)application withOptions:(NSDictionary *)launchOptions {
    // 注册apns通知
    if (@available(iOS 10.0, *)) {
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge | UNAuthorizationOptionSound;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    } else if ([[UIDevice currentDevice].systemVersion floatValue] < 10.0 ) {
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert) categories:nil];
    }
    /*
     *  launchingOption 启动参数.
     *  appKey 一个JPush 应用必须的,唯一的标识.
     *  channel 发布渠道. 可选.
     *  isProduction 是否生产环境. 如果为开发状态,设置为 NO; 如果为生产状态,应改为 YES.
     *  advertisingIdentifier 广告标识符（IDFA） 如果不需要使用IDFA，传nil.
     * 此接口必须在 App 启动时调用, 否则 JPush SDK 将无法正常工作.
     */
    
    // 如不需要使用IDFA，advertisingIdentifier 可为nil
    // 注册极光推送
    [JPUSHService setupWithOption:launchOptions appKey:JPUSHAPPKEY channel:channel apsForProduction:isProduction advertisingIdentifier:nil];
    
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0) {
            // iOS10获取registrationID放到这里了, 可以存到缓存里, 用来标识用户单独发送推送
            [[NSUserDefaults standardUserDefaults] setObject:registrationID forKey:@"registrationID"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        } else {
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
}

#pragma mark 注册推送回调获取 DeviceToken
/**
 注册成功
 
 @param application  ...
 @param deviceToken ...
 */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [JPUSHService registerDeviceToken:deviceToken];
    
}

/**
 注册失败
 
 @param application ...
 @param error ...
 */
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
 
}

#pragma mark 收到远程推送
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler {
    [JPUSHService handleRemoteNotification:userInfo];
    if ([[UIDevice currentDevice].systemVersion floatValue] < 10.0 && application.applicationState > 0) {
        ///ios10 以下
        if ([userInfo[@"type"] isEqualToString:@"moment"]) {
           
        }
    } else {
        //ios10 程序在后台收到推送
    }
   
    completionHandler(UIBackgroundFetchResultNewData);
}


#pragma mark iOS10: 收到推送消息调用(iOS10是通过Delegate实现的回调)
/**
 当程序在前台时, 收到推送弹出的通知
 
 @param center ...
 @param notification ...
 @param completionHandler ...
 */
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    NSDictionary * userInfo = notification.request.content.userInfo;
    if (@available(iOS 10.0, *)) {
            // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
            completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert|UNNotificationPresentationOptionSound);
        }
    if (@available(iOS 10.0, *)) {
        if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            //如果是远程推送
            [JPUSHService handleRemoteNotification:userInfo];
        }
    } 
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
    //必须实现这个方法，点击的时候下面的方法才会被调用
    if (@available(iOS 10.0, *)) {
        completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert);
    }
}

/**
 点击alert时候处理逻辑

 @param center ...
 @param response ...
 @param completionHandler ...
 */
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if (@available(iOS 10.0, *)) {
        if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]){
            [JPUSHService handleRemoteNotification:userInfo];
        }
    }
   
     // 系统要求执行这个方法
     completionHandler();
}

@end
